import { useState, useMemo, useEffect } from "react";
import { trendCardService } from "../services/trendCardService";
import { TrendCardData } from "../types/trendCard";
import { formatNumber } from "../utils/numberFormat";
import { isValidTrendCardData, isValidCardContent } from "../utils/cardUtils";

const TIME_RANGES = [
  { label: "近一月", value: "1m" },
  { label: "近三月", value: "3m" },
  { label: "近一年", value: "1y" },
  { label: "近三年", value: "3y" }
];

// 时间范围映射到中文
const TIME_RANGE_MAP: { [key: string]: string } = {
  "1m": "近一月",
  "3m": "近三月", 
  "1y": "近一年",
  "3y": "近三年"
};

// 中文时间范围映射到tab值
const CHINESE_TIME_RANGE_TO_TAB_MAP: { [key: string]: string } = {
  "近一月": "1m",
  "近三月": "3m", 
  "近一年": "1y",
  "近三年": "3y"
};

// 替换cardContent中的时间范围
const replaceTimeRangeInCardContent = (cardContent: string, newTimeRange: string): string => {
  // 支持的时间范围模式 - 按长度排序，避免部分匹配问题
  const timeRangePatterns = [
    /近五年/g,
    /近三年/g,
    /近六月/g,
    /近一年/g,
    /近三月/g,
    /近一月/g
  ];
  
  let modifiedContent = cardContent;
  
  // 替换所有可能的时间范围
  timeRangePatterns.forEach(pattern => {
    modifiedContent = modifiedContent.replace(pattern, newTimeRange);
  });
  
  // 如果没有找到任何时间范围，在合适的位置添加
  if (modifiedContent === cardContent) {
    // 在合适的位置添加时间范围
    if (cardContent.includes('-')) {
      // 如果已经有分隔符，在分隔符后添加时间范围
      const parts = cardContent.split('-');
      if (parts.length >= 2) {
        parts.splice(1, 0, newTimeRange);
        modifiedContent = parts.join('-');
      } else {
        modifiedContent = `${cardContent}-${newTimeRange}`;
      }
    } else {
      // 如果没有分隔符，直接添加
      modifiedContent = `${cardContent}-${newTimeRange}`;
    }
  }
  
  return modifiedContent;
};

type TrendData = {
  date: string;
  values: { [key: string]: number };
};

// 将API数据转换为TrendData格式的辅助函数
function convertApiDataToTrendData(trendData: TrendCardData): TrendData[] {
  if (!trendData || !trendData.dataLines || trendData.dataLines.length === 0) {
    return [];
  }

  // 找到最长的数据数组长度
  const maxLength = Math.max(...trendData.dataLines.map(line => line.data.length));
  
  const result: TrendData[] = [];
  
  for (let i = 0; i < maxLength; i++) {
    const values: { [key: string]: number } = {};
    let date = '';
    
    // 收集所有数据线在该时间点的值
    trendData.dataLines.forEach(line => {
      const point = line.data[i];
      if (point) {
        values[line.name] = point.value;
        if (!date) date = point.date;
      }
    });
    
    result.push({
      date,
      values
    });
  }
  
  return result;
}

export default function TrendCardMobile({ cardContent, data }: { cardContent: string, data?: any }) {
  const [range, setRange] = useState("1m");
  const [trendData, setTrendData] = useState<any | null>(data || null);
  const [hoverIndex, setHoverIndex] = useState<number | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchData = async (timeRange?: string) => {
    // 如果有时间范围参数，替换cardContent中的时间范围
    let modifiedCardContent = cardContent;
    if (timeRange) {
      const chineseTimeRange = TIME_RANGE_MAP[timeRange];
      if (chineseTimeRange) {
        modifiedCardContent = replaceTimeRangeInCardContent(cardContent, chineseTimeRange);
      }
    }
    
    // 只有在以下情况才调用API：
    // 1. 时间范围发生了切换（modifiedCardContent !== cardContent）
    // 2. 没有传入初始数据且需要首次加载（!data && cardContent === modifiedCardContent）
    const shouldFetchFromAPI = (modifiedCardContent !== cardContent) || (!data && cardContent === modifiedCardContent);
    
    if (shouldFetchFromAPI) {
      if (!isValidCardContent(modifiedCardContent)) {
        setTrendData(null);
        setLoading(false);
        setError(null);
        return;
      }
      
      setLoading(true);
      setError(null);
      
      try {
        const d = await trendCardService.getTrendCardByCardContent(modifiedCardContent);
        if (isValidTrendCardData(d)) {
          setTrendData(d);
          setError(null);
          
          // 根据API返回的时间范围设置对应的tab
          if (d && d.timeRange && CHINESE_TIME_RANGE_TO_TAB_MAP[d.timeRange]) {
            setRange(CHINESE_TIME_RANGE_TO_TAB_MAP[d.timeRange]);
          }
        } else {
          setTrendData(null);
          setError('暂无数据');
        }
      } catch (err) {
        console.error('获取趋势图数据失败:', err);
        setTrendData(null);
        setError('数据加载失败');
      } finally {
        setLoading(false);
      }
    } else {
      // 直接使用传入的数据，不再调用API
      setTrendData(data);
      setLoading(false);
      setError(null);
      
      // 如果有传入的数据，也根据其时间范围设置tab
      if (data && data.timeRange && CHINESE_TIME_RANGE_TO_TAB_MAP[data.timeRange]) {
        setRange(CHINESE_TIME_RANGE_TO_TAB_MAP[data.timeRange]);
      }
    }
  };

  // 初始加载数据
  useEffect(() => {
    // 如果有传入的data，直接使用，不调用API
    if (data) {
      setTrendData(data);
      setLoading(false);
      setError(null);
      
      // 根据数据的时间范围设置对应的tab
      if (data.timeRange && CHINESE_TIME_RANGE_TO_TAB_MAP[data.timeRange]) {
        setRange(CHINESE_TIME_RANGE_TO_TAB_MAP[data.timeRange]);
      }
    } else {
      // 只有在没有传入data时才调用API获取数据
      fetchData();
    }
  }, [cardContent]); // 移除data依赖，避免data变化时重复调用

  // 单独处理data的变化
  useEffect(() => {
    if (data) {
      setTrendData(data);
      setLoading(false);
      setError(null);
      
      // 根据数据的时间范围设置对应的tab
      if (data.timeRange && CHINESE_TIME_RANGE_TO_TAB_MAP[data.timeRange]) {
        setRange(CHINESE_TIME_RANGE_TO_TAB_MAP[data.timeRange]);
      }
    }
  }, [data]);

  // 时间范围切换处理
  const handleRangeChange = (newRange: string) => {
    setRange(newRange);
    fetchData(newRange);
  };

  // 转换数据格式
  const chartData = useMemo(() => {
    if (!trendData) return [];
    return convertApiDataToTrendData(trendData);
  }, [trendData]);

  if (loading) {
    return (
      <div style={{ background: "#fff", borderRadius: 12, padding: 12, boxShadow: "0 2px 8px rgba(0,0,0,0.06)", maxWidth: 420, margin: "0 auto" }}>
        <div style={{ textAlign: "center", color: "#666", fontSize: 14 }}>加载中...</div>
      </div>
    );
  }

  // 当没有有效数据时，直接返回null隐藏卡片
  if (error || !isValidTrendCardData(trendData) || chartData.length === 0) {
    return null;
  }

  // 计算所有数据的最大值和最小值
  const allValues: number[] = chartData.flatMap(d => Object.values(d.values));
  const maxY: number = Math.max(...allValues, 0);
  const minY: number = Math.min(...allValues, 0);
  const rangeY: number = maxY - minY || 1;

  // 悬浮点数据
  const hoverData = hoverIndex !== null && chartData[hoverIndex] ? chartData[hoverIndex] : chartData[chartData.length - 1];

  // 计算当前hover点的x坐标百分比
  const len = chartData.length;
  const hoverX = hoverIndex !== null && len > 1 ? (hoverIndex / (len - 1)) * 100 : 0;

  // Y轴宽度常量
  const Y_AXIS_WIDTH = 45; // 缩小Y轴宽度，充分利用空间

  // 主图y坐标范围
  const CHART_Y_TOP = 12; // 10/100*120
  const CHART_Y_BOTTOM = 108; // 90/100*120
  const CHART_Y_HEIGHT = CHART_Y_BOTTOM - CHART_Y_TOP; // 96

  // 新增：带Y轴偏移的折线生成函数，放在组件内部，能访问chartData、minY、rangeY、Y_AXIS_WIDTH
  function genPathWithYAxisOffset(lineName: string, _color: string): string {
    const len = chartData.length;
    if (len === 0) return '';
    return chartData.map((d, i) => {
      const x = Y_AXIS_WIDTH + (len > 1 ? (i / (len - 1)) * (420 - Y_AXIS_WIDTH) : 0);
      const value = Number(d.values[lineName] || 0);
      const y = CHART_Y_BOTTOM - ((value - minY) / rangeY) * CHART_Y_HEIGHT;
      return i === 0 ? `M ${formatNumber(x, 2)} ${formatNumber(y, 2)}` : `L ${formatNumber(x, 2)} ${formatNumber(y, 2)}`;
    }).join(' ');
  }

  return (
    <div style={{ background: "#fff", borderRadius: 12, padding: 12, boxShadow: "0 2px 8px rgba(0,0,0,0.06)", maxWidth: 420, margin: "0 auto" }}>
      
      {/* 基金名称和指标 */}
      {trendData?.title && (
        <div style={{ marginBottom: 8 }}>
          <h4 style={{ 
            margin: 0, 
            fontSize: 13, 
            fontWeight: 400, 
            color: "#9CA3AF", 
            lineHeight: "1.2"
          }}>
            {trendData.title}
          </h4>
          {trendData.subtitle && (
            <h3 style={{ 
              margin: "4px 0 0 0", 
              fontSize: 15, 
              fontWeight: 500, 
              color: "#374151", 
              lineHeight: "1.3"
            }}>
              {trendData.subtitle}
            </h3>
          )}
        </div>
      )}
      
      {/* Tabs */}
      <div style={{ display: "flex", marginBottom: 8 }}>
        {TIME_RANGES.map(tab => (
          <div
            key={tab.value}
            style={{
              flex: 1,
              textAlign: "center",
              padding: "6px 0",
              borderBottom: range === tab.value ? "2px solid #3B82F6" : "2px solid transparent",
              color: range === tab.value ? "#3B82F6" : "#666",
              fontWeight: range === tab.value ? 600 : 400,
              fontSize: 14,
              cursor: "pointer"
            }}
            onClick={() => handleRangeChange(tab.value)}
          >
            {tab.label}
          </div>
        ))}
      </div>
      
      {/* 图例和数值 */}
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 8, gap: "8px" }}>
        {trendData!.dataLines.map((line: any, index: any) => (
          <div key={index} style={{ 
            color: line.color,
            minWidth: "80px",
            display: "flex",
            flexDirection: "column",
            alignItems: "center"
          }}>
            <span style={{ fontSize: "11px", marginBottom: "2px" }}>{line.name}</span>
            <span style={{ 
              color: hoverData?.values[line.name] >= 0 ? "#dc2626" : "#16a34a",
              fontWeight: "500",
              minWidth: "50px",
              textAlign: "center"
            }}>
              {formatNumber(hoverData?.values[line.name] || 0, 2)}%
            </span>
          </div>
        ))}
      </div>
      
      {/* SVG趋势图 */}
      <div style={{ position: "relative", height: 120, marginBottom: 8, overflow: 'hidden' }}>
        <svg width="100%" height="100%" viewBox="0 0 420 120" preserveAspectRatio="none" style={{ position: "absolute", top: 0, left: 0, width: "100%", height: "100%" }}>
          {/* 背景网格和Y轴刻度 */}
          <g>
            {[0, 0.25, 0.5, 0.75, 1].map((p, idx) => {
              // 计算Y轴刻度值
              const y = CHART_Y_TOP + CHART_Y_HEIGHT * p;
              const value = maxY - (maxY - minY) * p;
              return (
                <g key={idx}>
                  {/* 刻度线从Y_AXIS_WIDTH到420 */}
                  <line x1={Y_AXIS_WIDTH} x2={420} y1={y} y2={y} stroke="#e5e7eb" strokeWidth="1" />
                  {/* Y轴刻度数值，主图左侧右对齐，带百分号 */}
                  <text x={Y_AXIS_WIDTH - 8} y={y + 3} fontSize="10" fontWeight="400" fill="#888888" textAnchor="end">{formatNumber(value, 2)}%</text>
                </g>
              );
            })}
          </g>
          {/* 动态渲染所有折线 */}
          {trendData!.dataLines.map((line: any, index: any) => (
            <path 
              key={index}
              d={genPathWithYAxisOffset(line.name, line.color)}
              fill="none" 
              stroke={line.color} 
              strokeWidth="1" 
            />
          ))}
          
          {/* 悬浮点竖线和圆点 */}
          {chartData.map((d, i) => {
            const x = Y_AXIS_WIDTH + (len > 1 ? (i / (len - 1)) * (420 - Y_AXIS_WIDTH) : 0);
            const firstLineName = trendData!.dataLines[0]?.name;
            const yMain = firstLineName ? CHART_Y_BOTTOM - ((d.values[firstLineName] - minY) / rangeY) * CHART_Y_HEIGHT : 60;
            return (
              <g key={i}>
                {hoverIndex === i && (
                  <>
                    {/* 竖线用SVG渲染，y1=CHART_Y_TOP, y2=CHART_Y_BOTTOM */}
                    <line x1={x} x2={x} y1={CHART_Y_TOP} y2={CHART_Y_BOTTOM} stroke="#8884d8" strokeDasharray="4,4" strokeWidth={2} />
                    <circle cx={x} cy={yMain} r={4} fill={trendData!.dataLines[0]?.color || "#3B82F6"} />
                  </>
                )}
                {/* 响应鼠标事件的透明区域 */}
                <rect x={x - 7} y={CHART_Y_TOP} width={14} height={CHART_Y_HEIGHT} fill="transparent"
                  style={{ cursor: 'pointer' }}
                  onMouseEnter={() => setHoverIndex(i)}
                  onMouseLeave={() => setHoverIndex(null)}
                />
              </g>
            );
          })}
        </svg>
        {/* hover时显示日期，跟随hover移动 */}
        {hoverIndex !== null && chartData[hoverIndex] && (
          (() => {
            // 计算tooltip的left像素
            const tooltipLeft = Y_AXIS_WIDTH + (hoverX * (420 - Y_AXIS_WIDTH) / 100);
            const containerWidth = 420;
            const tooltipWidth = 80; // 预估tooltip宽度
            let tooltipTransform = "translateX(-50%)";
            if (tooltipLeft > containerWidth - tooltipWidth) {
              tooltipTransform = "translateX(-100%)";
            } else if (tooltipLeft < tooltipWidth) {
              tooltipTransform = "translateX(0)";
            }
            return (
              <div 
                style={{
                  position: "absolute",
                  left: `${tooltipLeft}px`,
                  top: `${CHART_Y_TOP}px`,
                  transform: tooltipTransform,
                  background: "white",
                  padding: "6px 12px",
                  borderRadius: "6px",
                  fontSize: "14px",
                  color: "#374151",
                  boxShadow: "0 1px 3px rgba(0,0,0,0.1)",
                  border: "1px solid #e5e7eb",
                  pointerEvents: "none",
                  whiteSpace: "nowrap"
                }}
              >
                {formatDate(chartData[hoverIndex].date)}
              </div>
            );
          })()
        )}
      </div>
      {/* 日期显示 - 左右下角用chartData首尾 */}
      {chartData.length > 0 && (
        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 10, color: "#9CA3AF", marginTop: 8 }}>
          <span>{formatDate(chartData[0].date)}</span>
          <span style={{ flex: 1, textAlign: 'center' }}>{formatDate(chartData[Math.floor(chartData.length / 2)].date)}</span>
          <span>{formatDate(chartData[chartData.length-1].date)}</span>
        </div>
      )}
    </div>
  );
}

// 新增日期格式化函数
function formatDate(dateStr: string) {
  const d = new Date(dateStr);
  if (isNaN(d.getTime())) return '--';
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
} 